package yannan.voiplock4ble.fragment;


import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import yannan.voiplock4ble.R;
import yannan.voiplock4ble.adapter.LockVeinKeyAdapter;
import yannan.voiplock4ble.adapter.base.RecyclerViewBaseAdapter;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.LockBaseFragment;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.LockKeyBean;
import yannan.voiplock4ble.db.MyDBHelper;
import yannan.voiplock4ble.eventbus.BaseEventMsg;
import yannan.voiplock4ble.eventbus.ConnectFailedMsg;
import yannan.voiplock4ble.eventbus.DelVeinMsg;
import yannan.voiplock4ble.eventbus.OperAdminMsg;
import yannan.voiplock4ble.eventbus.OperVeinMsg;
import yannan.voiplock4ble.eventbus.VeinKeyListMsg;
import yannan.voiplock4ble.service.ble.BleOperUtils;
import yannan.voiplock4ble.service.ble.BleUtils;
import yannan.voiplock4ble.task.CompareTimeTask;
import yannan.voiplock4ble.task.UpLoadLockKeyTask;
import yannan.voiplock4ble.utils.LogUtils;
import yannan.voiplock4ble.utils.OperLockUtils;
import yannan.voiplock4ble.utils.PopShowUtils;
import yannan.voiplock4ble.utils.ToastUtils;
import yannan.voiplock4ble.view.RecyclerSupportViewEmpty;

/**
 * 说明：指静脉钥匙
 * 作者：mainTel
 * 时间：2016/8/24 09:39
 * 备注：
 */
@Content(R.layout.fragment_lock_key_content)
public class LockKeyVeinFragment extends LockBaseFragment implements SwipeRefreshLayout.OnRefreshListener, RecyclerViewBaseAdapter.OnItemClickListener {
    @Bind(R.id.lv_lock_record)
    RecyclerSupportViewEmpty veinRecyclerView;
    @Bind(R.id.lv_lock_record_empty_view)
    ScrollView emptyView;
    @Bind((R.id.lv_lock_record_empty_textview))
    TextView lv_lock_record_empty_textview;
    @Bind(R.id.swipe_content)
    SwipeRefreshLayout swipeRefresh;
    @Bind(R.id.iv_blue_icon)
    ImageView iv_blue_icon;
    LockVeinKeyAdapter adapter;
    LockBean nowLock;
    boolean isNew;
    boolean isHidden;
    LockKeyBean operKeyBean;

    @Override
    public void initdata() {
        adapter = new LockVeinKeyAdapter(new ArrayList<LockKeyBean>(), mContext, veinRecyclerView);
        veinRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        veinRecyclerView.setEmptyView(emptyView);
        veinRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
        lv_lock_record_empty_textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!swipeRefresh.isRefreshing()) {
                    swipeRefresh.setRefreshing(true);
                    getVeinKeyList();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("LockKeyVeinFragment");
        if (!isHidden)
            checkAndLoadData();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("LockKeyVeinFragment");
    }

    private void checkAndLoadData() {
        if (nowLock != null) {
            if (!nowLock.lockserialId.equals(mainActivity.lockBeanNow.lockserialId)) {
                nowLock = mainActivity.lockBeanNow;
                getVeinKeyList();
            }
        } else {
            nowLock = mainActivity.lockBeanNow;
            getVeinKeyList();
        }
    }

    /**
     * 获取指静脉列表
     */
    private void getVeinKeyList() {
        getLocalVeinKeyList();
        if (BleOperUtils.checkBleConnect(nowLock)) {
            iv_blue_icon.setBackgroundResource(R.drawable.ic_bluetooth_connected);
            isNew = true;
            MyApplication.getInterface().isHaveConnected = true;
            mHandler.sendEmptyMessageDelayed(GET_VEIN_KEY_LIST_TIME_OUT, 8000);
            if (MyDBHelper.copyLockKeyList(nowLock.lockserialId, "0"))
                mainActivity.mBleService.sendOrder(BleUtils.getFingerUser(MyApplication.getInterface().mConnectLock.contentToken, 1));
            swipeRefresh.setRefreshing(false);
        } else {
            MyApplication.getInterface().isHaveConnected = false;
            iv_blue_icon.setBackgroundResource(R.drawable.ic_bluetooth_disconnect);
            mHandler.sendEmptyMessageDelayed(GET_VEIN_KEY_LIST_TIME_OUT, 5000);
            //对比上次刷新的时间
            CompareTimeTask.create(mainActivity.lockBeanNow.lockserialId, CompareTimeTask.TYPE_VEIN).start();
        }
    }

    /**
     * 获取本地
     */
    private void getLocalVeinKeyList() {
        List<LockKeyBean> list = MyDBHelper.getLockKeyBeanListByID(nowLock.lockserialId, "0");
        adapter.upDate(list);
    }

    @Override
    public void initView() {
        swipeRefresh.setOnRefreshListener(this);
    }

    @Override
    public void onRefresh() {
        getVeinKeyList();
    }

    @Override
    public void onItemClick(View view, final int poi) {
        final LockKeyBean bean = adapter.getItemByPosition(poi);
        switch (view.getId()) {
            case R.id.rl_del:
                if (MyApplication.getInterface().mConnectLock != null) {
                    operKeyBean = bean;
                    BleOperUtils.delKey(bean, mContext, mainActivity.mBleService);
                } else {
                    ToastUtils.showToast(mContext, "门锁未连接");
                }
                break;
            case R.id.rl_admin:
                if (MyApplication.getInterface().mConnectLock != null) {
                    operKeyBean = bean;
                    BleOperUtils.editAdmin(bean, mContext, mainActivity.mBleService);
                } else {
                    ToastUtils.showToast(mContext, "门锁未连接");
                }
                break;
            case R.id.rl_remark:
                PopShowUtils.editRemarks(mContext, bean, new PopShowUtils.IOnEditName() {
                    @Override
                    public void onChange(String msg) {
                        OperLockUtils.editKeyRemarks(bean, msg);
                        adapter.upDate(MyDBHelper.getLockKeyBeanListByID(nowLock.lockserialId, "0"));
                        UpLoadLockKeyTask.create(nowLock.lockserialId, "0").start();
                    }
                });
                break;
            case R.id.rl_ban:
                if (MyApplication.getInterface().mConnectLock != null) {
                    operKeyBean = bean;
                    BleOperUtils.banPickKey(bean, mContext, mainActivity.mBleService);
                } else {
                    ToastUtils.showToast(mContext, "门锁未连接");
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String msg) {
        if (msg.equals("upDateVeinKey")) {
            adapter.upDate(MyDBHelper.getLockKeyBeanListByID(nowLock.lockserialId, "0"));
        } else if (msg.equals("cancelRefresh")) {
            swipeRefresh.setRefreshing(false);
        } else if (msg.equals("changeLockMsg")) {
            adapter.clear();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEventMsg msg) {
        if (msg instanceof VeinKeyListMsg) {
            VeinKeyListMsg bean = (VeinKeyListMsg) msg;
            //不为空的时候
            if (bean.keyBean != null) {
                if (isNew ) {
                    //删除所有用户
                    MyDBHelper.delLockKeyAll(nowLock.lockserialId, "0");
                    swipeRefresh.setRefreshing(false);
                    isNew = false;
                    adapter.clear();
                }
                //存储所有用户
                MyDBHelper.installKeyBean(bean.keyBean);
                mHandler.removeMessages(GET_VEIN_KEY_LIST_OVER);
                mHandler.sendEmptyMessageDelayed(GET_VEIN_KEY_LIST_OVER, 2000);
            } else {
                //不是完整的消息的时候，判断是不是删除了全部之后发过来的消息
                if (bean.isClear) {
                    MyDBHelper.delLockKeyAll(nowLock.lockserialId, "0");
                    swipeRefresh.setRefreshing(false);
                    isNew = false;
                    adapter.clear();
                }
            }
        } else if (msg instanceof DelVeinMsg) {
            DelVeinMsg veinMsg = (DelVeinMsg) msg;
            if (veinMsg.delKey.result == 1) {
                ToastUtils.showToast(mContext, "删除成功！");
                if (operKeyBean != null) {
                    OperLockUtils.delLockKeyResult(operKeyBean);
                    adapter.upDate(MyDBHelper.getLockKeyBeanListByID(nowLock.lockserialId, "0"));
                    getVeinKeyList();
                }
            } else {
                ToastUtils.showToast(mContext, "删除失败");
            }
        } else if (msg instanceof OperVeinMsg) {
            OperVeinMsg operVeinMsg = (OperVeinMsg) msg;
            if (operVeinMsg.isSuc) {
                ToastUtils.showToast(mContext, "操作成功");
                if (operKeyBean != null) {
                    OperLockUtils.banPickLockKeyResult(operKeyBean);
                    adapter.upDate(MyDBHelper.getLockKeyBeanListByID(nowLock.lockserialId, "0"));
                    getVeinKeyList();
                }
            } else {
                ToastUtils.showToast(mContext, "操作失败");
            }
        } else if (msg instanceof OperAdminMsg) {
            OperAdminMsg operAdminMsg = (OperAdminMsg) msg;
            if (operAdminMsg.isSuc == 0) {
                ToastUtils.showToast(mContext, "操作成功");
                if (operKeyBean != null) {
                    OperLockUtils.changeKeyAdmin(operKeyBean);
                    adapter.upDate(MyDBHelper.getLockKeyBeanListByID(nowLock.lockserialId, "0"));
                    getVeinKeyList();
                } else {
                    ToastUtils.showToast(mContext, "操作失败");
                }
            }
        } else if (msg instanceof ConnectFailedMsg) {
            ConnectFailedMsg connectFailedMsg = (ConnectFailedMsg) msg;
            LogUtils.i("LockKeyVeinFragment==" + connectFailedMsg.isConnect);
            if (connectFailedMsg.isConnect) {
                iv_blue_icon.setBackgroundResource(R.drawable.ic_bluetooth_connected);
                if (!isHidden) {
                    mainActivity.fab_add.setVisibility(View.VISIBLE);
                    nowLock=mainActivity.lockBeanNow;
                    getVeinKeyList();
                }
            } else {
                iv_blue_icon.setBackgroundResource(R.drawable.ic_bluetooth_disconnect);
                if (!isHidden)
                    mainActivity.fab_add.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHidden = hidden;
        if (!hidden) {
            checkAndLoadData();
        }
    }

    static final int GET_VEIN_KEY_LIST_TIME_OUT = 1001;
    static final int GET_VEIN_KEY_LIST_OVER = 1002;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_VEIN_KEY_LIST_TIME_OUT:
                    swipeRefresh.setRefreshing(false);
                    break;
                case GET_VEIN_KEY_LIST_OVER:
                    getLocalVeinKeyList();
                    //接收完毕 上传
                    UpLoadLockKeyTask.create(nowLock.lockserialId, "0").start();
                    break;
            }
        }
    };
}
